package com.lsh.security.service.impl;

import com.lsh.security.entity.SysRole;
import com.lsh.security.entity.SysUser;
import com.lsh.security.repository.SysRoleRepository;
import com.lsh.security.repository.SysUserRepository;
import com.lsh.security.repository.SysUserRoleRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/8/18 1:35 下午
 * @desc ：SpringSecurity认证
 *          继承UserDetailsService接口 实现loadUserByUsername方法
 */
@Slf4j
@Service("userDetailsService")
public class UserDetailServiceImpl  implements UserDetailsService {

    @Autowired
    SysUserRepository userRepository;
    @Autowired
    SysRoleRepository roleRepository;
    @Autowired
    SysUserRoleRepository userRoleRepository;

    /**
     * 根据账号查询用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //暂时模拟构建一个UserDetails
        //UserDetails build = User.withUsername("zs").password("$2a$10$FFYhLLG2LWqkIHo0KgeRbuO1xt93cFn7Zce0TzmQY545uJcEL6Hgu").authorities("p1", "p3").build();

        //查询数据库
        SysUser user = userRepository.findTopByName(username);
        if (user == null){
            //如果用户不存在返回空
            return null;
        }
        //根据用户ID查询 用户-角色关联表 获得角色ID 集合
        List<Integer> roleIdsByUserId = userRoleRepository.findRoleIdsByUserId(user.getId());

        //根据角色ID 查询 角色表
        List<SysRole> roles = roleRepository.findSysRolesByIdIn(roleIdsByUserId);

        Collection<GrantedAuthority> authorities = new ArrayList<>();
        roles.stream().forEach(x ->{
            authorities.add(new SimpleGrantedAuthority(x.getName()));
            log.info("RoleName:"+x.getName());
        });
        log.info("该用户的角色有："+authorities.size()+" 个");
        /**
         * 返回值是UserDetails，这是一个接口，
         * 一般使用它的子类org.springframework.security.core.userdetails.User，
         * 它有三个参数，分别是用户名、密码和权限集
         */
        return new User(user.getName(), user.getPassword(), authorities);

    }
}
